package com.zsh.mvc.controller;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.UUID;

/**
 * @author zsh
 * @Description
 * @create 2022-01-26 17:59
 */

@Controller
public class FileUpAndDownController {

    @RequestMapping("/testDown")
    public ResponseEntity<byte[]> testDown(HttpSession session) throws IOException {

        ServletContext servletContext = session.getServletContext();
        String realPath = servletContext.getRealPath("/static/img/qq头像.jpg");

        FileInputStream is = new FileInputStream(realPath);
        byte[] bytes = new byte[is.available()];  //获取文件的字节数

        is.read(bytes); //将流读档数组里

        //设置响应头
        MultiValueMap<String, String> headers = new HttpHeaders();

        //设置下载方式和下载文件名
        headers.add("Content-Disposition","attachment;filename=" + URLEncoder.encode("qq头像.jpg", "UTF-8"));

        //状态码
        HttpStatus statusCode = HttpStatus.OK;

        //创建ResponseEntity
        ResponseEntity<byte[]> responseEntity = new ResponseEntity<byte[]>(bytes,headers,statusCode);

        return responseEntity;


    }

    @RequestMapping("/testUp")
    public String testUp(MultipartFile photo,HttpSession session) throws IOException {
        String filename = photo.getOriginalFilename();

        //处理文件重名问题
        String suffixName = filename.substring(filename.lastIndexOf("."));
        filename = UUID.randomUUID().toString() + suffixName;

        ServletContext servletContext = session.getServletContext();
        String photoPath = servletContext.getRealPath("photo");
        File file = new File(photoPath);

        if (!file.exists()){
            file.mkdirs();
        }

        String finalPath = photoPath + File.separator + filename;

        //实现上传
        photo.transferTo(new File(finalPath));
        return "success";

    }
}
